use axum::Json;
use http::HeaderMap;
use serde_json::Value;
use sea_orm::{ query::*, sea_query::Expr, DbErr, DeleteResult, EntityTrait, FromQueryResult };
use crate::{auth::claims::get_id, code, query, sea_orm::connect};

use serde::{ Deserialize, Serialize };

#[derive(Debug, Deserialize, Serialize, FromQueryResult)]
pub struct Data {
    id:i32,
    create_user: i32
}

// 单个 = 用户删除自己创建的数据
pub async fn one_str<E:EntityTrait>(header: HeaderMap, entity:E, field:&str, value:&str) -> Result<Json<Value>, Json<Value>>{
    let conn = connect().await?;
    let table = entity.table_name();
    let user = get_id(header)?;
    let stmt = Statement::from_string(
        conn.get_database_backend(),
        format!("select create_user from {} where {}={} and create_user={}", table, field, &value, &user),
    );
    let rs:Result<Option<Data>,DbErr>= Data::find_by_statement(stmt).into_model().one(&conn).await;
    match rs {
        Ok(data) => {
            if let Some(_) = data {
                let stmt = Statement::from_string(
                    conn.get_database_backend(),
                    format!("delete from {} where {}={}", table, &field, &value),
                );
                let rs= conn.execute(stmt).await;
                code::send_ok(rs)
            }else{
                code::err(format!("只能本人执行删除操作"))
            }
        },
        Err(e) => code::sys(e.to_string())
    }
}
pub async fn one_i32<E:EntityTrait>(header: HeaderMap, entity:E, field:&str, value:i32) -> Result<Json<Value>, Json<Value>>{
    let conn = connect().await?;
    let table = entity.table_name();
    let user = get_id(header)?;
    let stmt = Statement::from_string(
        conn.get_database_backend(),
        format!("select create_user from {} where {}={} and create_user={}", table, field, &value, &user),
    );
    let rs:Result<Option<Data>,DbErr>= Data::find_by_statement(stmt).into_model().one(&conn).await;
    match rs {
        Ok(data) => {
            if let Some(_) = data {
                let stmt = Statement::from_string(
                    conn.get_database_backend(),
                    format!("delete from {} where {}={}", table, &field, &value),
                );
                let rs= conn.execute(stmt).await;
                code::send_ok(rs)
            }else{
                code::err(format!("只能本人执行删除操作"))
            }
        },
        Err(e) => code::sys(e.to_string())
    }
}
// 删除多个 = 用户删除自己创建的数据
pub async fn many_str<E:EntityTrait>(header: HeaderMap, entity:E, field:&str, value:Vec<String>) -> Result<Json<Value>, Json<Value>>{
    let conn = connect().await?;
    let table = entity.table_name();
    let user = get_id(header)?;
    let id = value.join(",");
    let stmt = Statement::from_string(
        conn.get_database_backend(),
        format!("select create_user from {} where id in({}) and create_user={}", table, &id, &user),
    );
    let rs:Result<Vec<Data>,DbErr>= Data::find_by_statement(stmt).into_model().all(&conn).await;

    match rs {
        Ok(data) => {
            if !data.is_empty() {
                let result: Result<DeleteResult,DbErr> = Delete::many(entity)
                .filter(Expr::cust( format!("{}=in({})", field, &id) ))
                .exec(&conn).await;
                code::send_ok(result)
            }else{
                code::err(format!("只能本人执行删除操作"))
            }
        },
        Err(e) => code::sys(e.to_string())
    }
}
pub async fn many_i32<E:EntityTrait>(header: HeaderMap, entity:E, field:&str, value:Vec<i32>) -> Result<Json<Value>, Json<Value>>{
    let conn = connect().await?;
    let table = entity.table_name();
    let user = get_id(header)?;
    let id = query::utils::vecstr_i32(value, "id")?;
    let id = id.join(",");
    let stmt = Statement::from_string(
        conn.get_database_backend(),
        format!("select create_user from {} where id in({}) and create_user={}", table, &id, &user),
    );
    let rs:Result<Vec<Data>,DbErr>= Data::find_by_statement(stmt).into_model().all(&conn).await;

    match rs {
        Ok(data) => {
            if !data.is_empty() {
                let result: Result<DeleteResult,DbErr> = Delete::many(entity)
                .filter(Expr::cust( format!("{}=in({})", field, &id) ))
                .exec(&conn).await;
                code::send_ok(result)
            }else{
                code::err(format!("只能本人执行删除操作"))
            }
        },
        Err(e) => code::sys(e.to_string())
    }
}